/*
 * ToDoNetView.java
 */

package todonet;

import java.awt.HeadlessException;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.event.TreeModelListener;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.RowMapper;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.filechooser.FileFilter;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import todonet.serializers.IToDoSerializer;
import todonet.serializers.SerializerFactory;

/**
 * The application's main frame.
 */
public class ToDoNetView extends FrameView {

    private boolean modifiedTask = false;

    public boolean isModifiedTask()
    {
        return modifiedTask;
    }

    public void setModifiedTask(boolean b)
    {
        modifiedTask = b;
        //timeRemainLabel.setText("До окончания осталось: " + selectedTask.getRemainDays() + " дней");
        toDoListTree.updateUI();
    }

    private ToDoTask rootTask = null;

    public ToDoTask getRootTask() {
        return rootTask;
    }

    public void setRootTask(ToDoTask rootTask) {
        this.rootTask = rootTask;
        int selectedPanel = ToDoListPane.getSelectedIndex();
        ToDoListPane.setTitleAt(selectedPanel, rootTask.toString());
        //toDoListTree.setModel(new ToDoListTreeModel(rootTask));
        toDoListTree.setModel(new DefaultTreeModel(rootTask));
        setSelectedTask(rootTask);
        setModifiedTask(false);
    }

    private ToDoTask selectedTask = rootTask;

    public void setSelectedTask(ToDoTask selectedTask) {
        this.selectedTask = selectedTask;
        taskTitleTextField.setText(selectedTask.getTitle());
        importantComboBox.setSelectedIndex(selectedTask.getImportant());
        percentCompleteSpinner.setValue(selectedTask.getSelfPercentComplete());
        if (selectedTask.getDateOfEnd() != null)
        {
            dateOfEndSpinner.setValue(selectedTask.getDateOfEnd());
            dateOfEndSpinner.setEnabled(true);
            dateOfEndCheckBox.setSelected(true);
        }
        else
        {
            dateOfEndSpinner.setValue(new Date());
            dateOfEndSpinner.setEnabled(false);
            dateOfEndCheckBox.setSelected(false);
        }
        timeRemainLabel.setText(selectedTask.getRemainTimeString());
        //toDoListTree.setSelectionPath(new TreePath(getRootTask()));
        toDoListTree.updateUI();
    }

    public ToDoTask getSelectedTask() {
        return selectedTask;
    }

    public Object[] getSelectedPathForTask(ToDoTask task) {
        if (task == null)
            return null;
        List<ToDoTask> pathList = new ArrayList<ToDoTask>();
        while (task != null) {
            pathList.add(pathList.size(), task);
            task = task.getParent();
        }
        return pathList.toArray();
    }
    
    public TreePath getSelectedPath() {
        return new TreePath(getSelectedPathForTask(getSelectedTask()));
    }

    public ToDoNetView(SingleFrameApplication app) {
        super(app);

        initComponents();

        setRootTask(new ToDoTask("Новая задача"));
        setModifiedTask(false);

        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String)(evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer)(evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = ToDoNetApp.getApplication().getMainFrame();
            aboutBox = new ToDoNetAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        ToDoNetApp.getApplication().show(aboutBox);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        ToDoListPane = new javax.swing.JTabbedPane();
        ToDoListPanel = new javax.swing.JPanel();
        editToolBar = new javax.swing.JToolBar();
        addTaskButton = new javax.swing.JButton();
        addSubTaskButton = new javax.swing.JButton();
        deleteTaskButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        toDoListTree = new javax.swing.JTree();
        taskTitleLabel = new javax.swing.JLabel();
        jSeparator2 = new javax.swing.JSeparator();
        taskTitleTextField = new javax.swing.JTextField();
        importantLabel = new javax.swing.JLabel();
        importantComboBox = new javax.swing.JComboBox();
        percentCompleteSpinner = new javax.swing.JSpinner();
        percentCompleteLabel = new javax.swing.JLabel();
        dateOfEndSpinner = new javax.swing.JSpinner();
        timeRemainLabel = new javax.swing.JLabel();
        fileToolBar = new javax.swing.JToolBar();
        newToDoListToolButton = new javax.swing.JButton();
        openFromFileToolButton = new javax.swing.JButton();
        saveToFileToolButton = new javax.swing.JButton();
        commitChangesButton = new javax.swing.JButton();
        dateOfEndCheckBox = new javax.swing.JCheckBox();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        newListMenuItem = new javax.swing.JMenuItem();
        openFromFileMenuItem = new javax.swing.JMenuItem();
        saveToFileMenuItem = new javax.swing.JMenuItem();
        saveAsToFileMenuItem = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JPopupMenu.Separator();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();

        mainPanel.setName("mainPanel"); // NOI18N

        ToDoListPane.setName("ToDoListPane"); // NOI18N

        ToDoListPanel.setName("ToDoListPanel"); // NOI18N

        editToolBar.setRollover(true);
        editToolBar.setName("editToolBar"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(todonet.ToDoNetApp.class).getContext().getResourceMap(ToDoNetView.class);
        addTaskButton.setIcon(resourceMap.getIcon("addTaskButton.icon")); // NOI18N
        addTaskButton.setText(resourceMap.getString("addTaskButton.text")); // NOI18N
        addTaskButton.setToolTipText(resourceMap.getString("addTaskButton.toolTipText")); // NOI18N
        addTaskButton.setFocusable(false);
        addTaskButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        addTaskButton.setName("addTaskButton"); // NOI18N
        addTaskButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        addTaskButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addTaskButtonActionPerformed(evt);
            }
        });
        editToolBar.add(addTaskButton);

        addSubTaskButton.setIcon(resourceMap.getIcon("addSubTaskButton.icon")); // NOI18N
        addSubTaskButton.setText(resourceMap.getString("addSubTaskButton.text")); // NOI18N
        addSubTaskButton.setToolTipText(resourceMap.getString("addSubTaskButton.toolTipText")); // NOI18N
        addSubTaskButton.setFocusable(false);
        addSubTaskButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        addSubTaskButton.setName("addSubTaskButton"); // NOI18N
        addSubTaskButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        addSubTaskButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addSubTaskButtonActionPerformed(evt);
            }
        });
        editToolBar.add(addSubTaskButton);

        deleteTaskButton.setIcon(resourceMap.getIcon("deleteTaskButton.icon")); // NOI18N
        deleteTaskButton.setText(resourceMap.getString("deleteTaskButton.text")); // NOI18N
        deleteTaskButton.setToolTipText(resourceMap.getString("deleteTaskButton.toolTipText")); // NOI18N
        deleteTaskButton.setFocusable(false);
        deleteTaskButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        deleteTaskButton.setName("deleteTaskButton"); // NOI18N
        deleteTaskButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        deleteTaskButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteTaskButtonActionPerformed(evt);
            }
        });
        editToolBar.add(deleteTaskButton);

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        toDoListTree.setName("toDoListTree"); // NOI18N
        toDoListTree.setRequestFocusEnabled(false);
        toDoListTree.setShowsRootHandles(true);
        toDoListTree.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
            public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
                toDoListTreeValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(toDoListTree);
        toDoListTree.putClientProperty("JTree.lineStype", "Angled");

        taskTitleLabel.setLabelFor(taskTitleTextField);
        taskTitleLabel.setText(resourceMap.getString("taskTitleLabel.text")); // NOI18N
        taskTitleLabel.setName("taskTitleLabel"); // NOI18N

        jSeparator2.setName("jSeparator2"); // NOI18N

        taskTitleTextField.setText(resourceMap.getString("taskTitleTextField.text")); // NOI18N
        taskTitleTextField.setName("taskTitleTextField"); // NOI18N

        importantLabel.setLabelFor(importantComboBox);
        importantLabel.setText(resourceMap.getString("importantLabel.text")); // NOI18N
        importantLabel.setName("importantLabel"); // NOI18N

        importantComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Низкая", "Нормальная", "Высокая" }));
        importantComboBox.setSelectedIndex(1);
        importantComboBox.setName("importantComboBox"); // NOI18N
        importantComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                importantComboBoxActionPerformed(evt);
            }
        });

        percentCompleteSpinner.setModel(new javax.swing.SpinnerNumberModel(Byte.valueOf((byte)0), Byte.valueOf((byte)0), Byte.valueOf((byte)100), Byte.valueOf((byte)10)));
        percentCompleteSpinner.setName("percentCompleteSpinner"); // NOI18N

        percentCompleteLabel.setLabelFor(percentCompleteSpinner);
        percentCompleteLabel.setText(resourceMap.getString("percentCompleteLabel.text")); // NOI18N
        percentCompleteLabel.setName("percentCompleteLabel"); // NOI18N

        dateOfEndSpinner.setModel(new javax.swing.SpinnerDateModel(new java.util.Date(), new java.util.Date(), null, java.util.Calendar.DAY_OF_WEEK));
        dateOfEndSpinner.setName("dateOfEndSpinner"); // NOI18N

        timeRemainLabel.setText(resourceMap.getString("timeRemainLabel.text")); // NOI18N
        timeRemainLabel.setName("timeRemainLabel"); // NOI18N

        fileToolBar.setRollover(true);
        fileToolBar.setName("fileToolBar"); // NOI18N

        newToDoListToolButton.setIcon(resourceMap.getIcon("newToDoListToolButton.icon")); // NOI18N
        newToDoListToolButton.setText(resourceMap.getString("newToDoListToolButton.text")); // NOI18N
        newToDoListToolButton.setToolTipText(resourceMap.getString("newToDoListToolButton.toolTipText")); // NOI18N
        newToDoListToolButton.setFocusable(false);
        newToDoListToolButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        newToDoListToolButton.setName("newToDoListToolButton"); // NOI18N
        newToDoListToolButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        newToDoListToolButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newToDoListToolButtonActionPerformed(evt);
            }
        });
        fileToolBar.add(newToDoListToolButton);

        openFromFileToolButton.setIcon(resourceMap.getIcon("openFromFileToolButton.icon")); // NOI18N
        openFromFileToolButton.setText(resourceMap.getString("openFromFileToolButton.text")); // NOI18N
        openFromFileToolButton.setToolTipText(resourceMap.getString("openFromFileToolButton.toolTipText")); // NOI18N
        openFromFileToolButton.setFocusable(false);
        openFromFileToolButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        openFromFileToolButton.setName("openFromFileToolButton"); // NOI18N
        openFromFileToolButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        openFromFileToolButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                openFromFileToolButtonActionPerformed(evt);
            }
        });
        fileToolBar.add(openFromFileToolButton);

        saveToFileToolButton.setIcon(resourceMap.getIcon("saveToFileToolButton.icon")); // NOI18N
        saveToFileToolButton.setText(resourceMap.getString("saveToFileToolButton.text")); // NOI18N
        saveToFileToolButton.setToolTipText(resourceMap.getString("saveToFileToolButton.toolTipText")); // NOI18N
        saveToFileToolButton.setFocusable(false);
        saveToFileToolButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        saveToFileToolButton.setName("saveToFileToolButton"); // NOI18N
        saveToFileToolButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        saveToFileToolButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveToFileToolButtonActionPerformed(evt);
            }
        });
        fileToolBar.add(saveToFileToolButton);

        commitChangesButton.setText(resourceMap.getString("commitChangesButton.text")); // NOI18N
        commitChangesButton.setActionCommand(resourceMap.getString("commitChangesButton.actionCommand")); // NOI18N
        commitChangesButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                commitChangesButtonActionPerformed(evt);
            }
        });

        dateOfEndCheckBox.setText(resourceMap.getString("dateOfEndCheckBox.text")); // NOI18N
        dateOfEndCheckBox.setName("dateOfEndCheckBox"); // NOI18N
        dateOfEndCheckBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                dateOfEndCheckBoxActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout ToDoListPanelLayout = new javax.swing.GroupLayout(ToDoListPanel);
        ToDoListPanel.setLayout(ToDoListPanelLayout);
        ToDoListPanelLayout.setHorizontalGroup(
            ToDoListPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(ToDoListPanelLayout.createSequentialGroup()
                .addComponent(fileToolBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(editToolBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(659, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, ToDoListPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(ToDoListPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(ToDoListPanelLayout.createSequentialGroup()
                        .addComponent(taskTitleLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(taskTitleTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 768, Short.MAX_VALUE))
                    .addGroup(ToDoListPanelLayout.createSequentialGroup()
                        .addComponent(importantLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(importantComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(percentCompleteLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(percentCompleteSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(dateOfEndCheckBox)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(dateOfEndSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(timeRemainLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 284, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(commitChangesButton)))
                .addContainerGap())
            .addComponent(jSeparator2, javax.swing.GroupLayout.DEFAULT_SIZE, 833, Short.MAX_VALUE)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 833, Short.MAX_VALUE)
        );
        ToDoListPanelLayout.setVerticalGroup(
            ToDoListPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(ToDoListPanelLayout.createSequentialGroup()
                .addGroup(ToDoListPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(fileToolBar, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(editToolBar, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 270, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(ToDoListPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(taskTitleLabel)
                    .addComponent(taskTitleTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(ToDoListPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(importantLabel)
                    .addComponent(importantComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(percentCompleteSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(percentCompleteLabel)
                    .addComponent(commitChangesButton)
                    .addComponent(dateOfEndCheckBox)
                    .addComponent(dateOfEndSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(timeRemainLabel))
                .addContainerGap())
        );

        ToDoListPane.addTab(resourceMap.getString("ToDoListPanel.TabConstraints.tabTitle"), ToDoListPanel); // NOI18N

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(ToDoListPane)
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(ToDoListPane, javax.swing.GroupLayout.DEFAULT_SIZE, 403, Short.MAX_VALUE)
        );

        ToDoListPane.getAccessibleContext().setAccessibleName(resourceMap.getString("ToDoListPane.AccessibleContext.accessibleName")); // NOI18N

        menuBar.setName("menuBar"); // NOI18N

        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        newListMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
        newListMenuItem.setIcon(resourceMap.getIcon("newListMenuItem.icon")); // NOI18N
        newListMenuItem.setText(resourceMap.getString("newListMenuItem.text")); // NOI18N
        newListMenuItem.setName("newListMenuItem"); // NOI18N
        newListMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newListMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(newListMenuItem);

        openFromFileMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
        openFromFileMenuItem.setIcon(resourceMap.getIcon("openFromFileMenuItem.icon")); // NOI18N
        openFromFileMenuItem.setText(resourceMap.getString("openFromFileMenuItem.text")); // NOI18N
        openFromFileMenuItem.setName("openFromFileMenuItem"); // NOI18N
        openFromFileMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                openFromFileMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(openFromFileMenuItem);

        saveToFileMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
        saveToFileMenuItem.setIcon(resourceMap.getIcon("saveToFileMenuItem.icon")); // NOI18N
        saveToFileMenuItem.setText(resourceMap.getString("saveToFileMenuItem.text")); // NOI18N
        saveToFileMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveToFileMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(saveToFileMenuItem);

        saveAsToFileMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        saveAsToFileMenuItem.setIcon(resourceMap.getIcon("saveAsToFileMenuItem.icon")); // NOI18N
        saveAsToFileMenuItem.setText(resourceMap.getString("saveAsToFileMenuItem.text")); // NOI18N
        saveAsToFileMenuItem.setName("saveAsToFileMenuItem"); // NOI18N
        saveAsToFileMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveAsToFileMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(saveAsToFileMenuItem);

        jSeparator1.setName("jSeparator1"); // NOI18N
        fileMenu.add(jSeparator1);

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(todonet.ToDoNetApp.class).getContext().getActionMap(ToDoNetView.class, this);
        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setText(resourceMap.getString("exitMenuItem.text")); // NOI18N
        exitMenuItem.setToolTipText(resourceMap.getString("exitMenuItem.toolTipText")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setIcon(resourceMap.getIcon("aboutMenuItem.icon")); // NOI18N
        aboutMenuItem.setText(resourceMap.getString("aboutMenuItem.text")); // NOI18N
        aboutMenuItem.setToolTipText(resourceMap.getString("aboutMenuItem.toolTipText")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 838, Short.MAX_VALUE)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusMessageLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 668, Short.MAX_VALUE)
                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(statusMessageLabel)
                    .addComponent(statusAnimationLabel)
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(3, 3, 3))
        );

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
    }// </editor-fold>//GEN-END:initComponents

    private void toDoListTreeValueChanged(javax.swing.event.TreeSelectionEvent evt) {//GEN-FIRST:event_toDoListTreeValueChanged
        ToDoTask task = (ToDoTask) evt.getPath().getLastPathComponent();
        setSelectedTask(task);
        addTaskButton.setEnabled(task.getParent() != null);
        deleteTaskButton.setEnabled(task.getParent() != null);

//        StringBuilder path = new StringBuilder();
//        for (Object o : evt.getPath().getPath())
//            path.append(o.toString() + " / ");
//        JOptionPane.showMessageDialog(this.getFrame(), path.toString());
    }//GEN-LAST:event_toDoListTreeValueChanged

    private void newToDoListToolButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newToDoListToolButtonActionPerformed
        newList();
    }//GEN-LAST:event_newToDoListToolButtonActionPerformed

    private void openFromFileToolButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openFromFileToolButtonActionPerformed
        openFile();
    }//GEN-LAST:event_openFromFileToolButtonActionPerformed

    private void openFromFileMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openFromFileMenuItemActionPerformed
        openFile();
    }//GEN-LAST:event_openFromFileMenuItemActionPerformed

    private void newListMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newListMenuItemActionPerformed
        newList();
    }//GEN-LAST:event_newListMenuItemActionPerformed

    private void saveToFileToolButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveToFileToolButtonActionPerformed
        saveToFile();
    }//GEN-LAST:event_saveToFileToolButtonActionPerformed

    private void saveToFileMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveToFileMenuItemActionPerformed
        saveToFile();
    }//GEN-LAST:event_saveToFileMenuItemActionPerformed

    private void saveAsToFileMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveAsToFileMenuItemActionPerformed
        saveToFileAs();
    }//GEN-LAST:event_saveAsToFileMenuItemActionPerformed

    private void importantComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_importantComboBoxActionPerformed

    }//GEN-LAST:event_importantComboBoxActionPerformed

    private void addTaskButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addTaskButtonActionPerformed
        if (getSelectedTask().getParent() == null)
            JOptionPane.showMessageDialog(this.getFrame(), "Невозножно добавить елемент рядом с корневым, попробуйте создать дочерний узел.", "Ошибка", JOptionPane.ERROR_MESSAGE);
        ToDoTask newTask = new ToDoTask("Новая задача");
        newTask.setParent(getSelectedTask().getParent());
        getSelectedTask().getParent().getChilds().add(newTask);
        setSelectedTask(newTask);
        toDoListTree.setExpandsSelectedPaths(true);
        toDoListTree.updateUI();
    }//GEN-LAST:event_addTaskButtonActionPerformed

    private void addSubTaskButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addSubTaskButtonActionPerformed
        ToDoTask newTask = new ToDoTask("Новая задача");
        newTask.setParent(getSelectedTask());
        getSelectedTask().getChilds().add(newTask);
        setSelectedTask(newTask);
    }//GEN-LAST:event_addSubTaskButtonActionPerformed

    private void deleteTaskButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteTaskButtonActionPerformed
        if (getSelectedTask().getParent() == null)
            JOptionPane.showMessageDialog(this.getFrame(), "Невозножно удалить корневой элемент!", "Ошибка", JOptionPane.ERROR_MESSAGE);
        ToDoTask newSelTask = getSelectedTask().getParent();
        getSelectedTask().getParent().getChilds().remove(getSelectedTask());
        setSelectedTask(newSelTask);
        setModifiedTask(true);
    }//GEN-LAST:event_deleteTaskButtonActionPerformed

    private void commitChangesButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_commitChangesButtonActionPerformed
        ToDoTask task = getSelectedTask();
        task.setTitle(taskTitleTextField.getText());
        task.setImportant(importantComboBox.getSelectedIndex());
        task.setPercentComplete((Byte) percentCompleteSpinner.getValue());
        task.setDateOfEnd(dateOfEndCheckBox.isSelected() ? (Date) dateOfEndSpinner.getValue() : null);
        if (task.getParent() == null)
        {
            int iSelTab = ToDoListPane.getSelectedIndex();
            ToDoListPane.setTitleAt(iSelTab, task.toString());
        }
        timeRemainLabel.setText(task.getRemainTimeString());
        toDoListTree.updateUI();
    }//GEN-LAST:event_commitChangesButtonActionPerformed

    private void dateOfEndCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dateOfEndCheckBoxActionPerformed
        dateOfEndSpinner.setEnabled(dateOfEndCheckBox.isSelected());
    }//GEN-LAST:event_dateOfEndCheckBoxActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTabbedPane ToDoListPane;
    private javax.swing.JPanel ToDoListPanel;
    private javax.swing.JButton addSubTaskButton;
    private javax.swing.JButton addTaskButton;
    private javax.swing.JButton commitChangesButton;
    private javax.swing.JCheckBox dateOfEndCheckBox;
    private javax.swing.JSpinner dateOfEndSpinner;
    private javax.swing.JButton deleteTaskButton;
    private javax.swing.JToolBar editToolBar;
    private javax.swing.JToolBar fileToolBar;
    private javax.swing.JComboBox importantComboBox;
    private javax.swing.JLabel importantLabel;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPopupMenu.Separator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JMenuItem newListMenuItem;
    private javax.swing.JButton newToDoListToolButton;
    private javax.swing.JMenuItem openFromFileMenuItem;
    private javax.swing.JButton openFromFileToolButton;
    private javax.swing.JLabel percentCompleteLabel;
    private javax.swing.JSpinner percentCompleteSpinner;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JMenuItem saveAsToFileMenuItem;
    private javax.swing.JMenuItem saveToFileMenuItem;
    private javax.swing.JButton saveToFileToolButton;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    private javax.swing.JLabel taskTitleLabel;
    private javax.swing.JTextField taskTitleTextField;
    private javax.swing.JLabel timeRemainLabel;
    private javax.swing.JTree toDoListTree;
    // End of variables declaration//GEN-END:variables

    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;

    private JDialog aboutBox;

    private File openedFile = null;

    public File getOpenedFile() {
        return openedFile;
    }

    public void setOpenedFile(File openedFile) {
        this.getFrame().setTitle("ToDoNet [" + openedFile.getName() + "]");
        this.openedFile = openedFile;
    }

    private void openFile() {
        if (isModifiedTask())
        {
            int dialogResult = JOptionPane.showConfirmDialog(this.getFrame(), "Сохранить изменения в файле?", "Вопрос", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
            switch (dialogResult)
            {
                case JOptionPane.YES_OPTION:
                    saveToFile();
                    break;
                case JOptionPane.CANCEL_OPTION:
                    return;
            }
        }
        JFileChooser openFileDialog = new JFileChooser();
        openFileDialog.setFileSelectionMode(JFileChooser.FILES_ONLY);
        openFileDialog.setFileFilter(new javax.swing.filechooser.FileFilter() {

            @Override
            public boolean accept(File f) {
                if (f.isFile())
                    return f.getName().endsWith(".todo.xml");
                else
                    return true;
            }

            @Override
            public String getDescription() {
                return "Файлы ToDoNet (.todo.xml)";
            }

        });
        openFileDialog.setDialogType(JFileChooser.OPEN_DIALOG);
        openFileDialog.setDialogTitle("Открыть файл...");
        int dialogResult = openFileDialog.showOpenDialog(this.getFrame());
        if (dialogResult == JFileChooser.APPROVE_OPTION)
        {
            File f = openFileDialog.getSelectedFile();
            if (!f.canRead())
            {
                JOptionPane.showMessageDialog(this.getFrame(), "Ошибка чтения. Файл недоступен для чтения.", "Ошибка", JOptionPane.ERROR_MESSAGE);
                return;
            }
            ToDoTask task = null;
            try
            {
                setOpenedFile(f);
                FileInputStream fis = new FileInputStream(f);
                IToDoSerializer serializer = SerializerFactory.createSerializer(f.getName());
                task = serializer.Load(fis);
                fis.close();
            }
            catch (Exception ex)
            {
                JOptionPane.showMessageDialog(this.getFrame(), ex.getLocalizedMessage(), "Ошибка", JOptionPane.ERROR_MESSAGE);
                return;
            }
            setRootTask(task);
        }
    }

    private void newList() {
         if (isModifiedTask())
         {
             int dialogResult = JOptionPane.showConfirmDialog(this.getFrame(), "Сохранить изменения в файле?", "Вопрос", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
             switch (dialogResult)
             {
                 case JOptionPane.YES_OPTION:
                     saveToFile();
                     break;
                 case JOptionPane.CANCEL_OPTION:
                     return;
             }
         }
         setOpenedFile(null);
         setRootTask(new ToDoTask("Новая задача"));
    }

    private void saveToFile(File f) throws HeadlessException {
        OutputStream fos = null;
        try {
            try {
                fos = new FileOutputStream(f);
                IToDoSerializer serializer = SerializerFactory.createSerializer(f.getName());
                serializer.Save(fos, rootTask);
            } catch (FileNotFoundException ex) {
                Logger.getLogger(ToDoNetView.class.getName()).log(Level.SEVERE, null, ex);
                JOptionPane.showMessageDialog(this.getFrame(), ex.getLocalizedMessage(), "Ошибка", JOptionPane.ERROR_MESSAGE);
            } finally {
                fos.close();
            }
        } catch (IOException ex) {
            Logger.getLogger(ToDoNetView.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(this.getFrame(), ex.getLocalizedMessage(), "Ошибка", JOptionPane.ERROR_MESSAGE);
        }
        setOpenedFile(f);
        setModifiedTask(false);
    }

    private void saveToFile() {
        if (getOpenedFile() != null && getOpenedFile().canWrite())
            saveToFile(getOpenedFile());
        else
            saveToFileAs();
    }

    private void saveToFileAs() {
        JFileChooser saveFileDialog = new JFileChooser();
        saveFileDialog.setDialogTitle("Выберите файл для сохранения...");
        saveFileDialog.setFileSelectionMode(JFileChooser.FILES_ONLY);
        saveFileDialog.setFileFilter(new FileFilter() {

            @Override
            public boolean accept(File f) {
                if (f.isFile())
                    return f.getName().toLowerCase().endsWith(".todo.xml");
                else
                    return true;
            }

            @Override
            public String getDescription() {
                return "Файлы ToDoNet (*.todo.xml)";
            }
        });
        saveFileDialog.setMultiSelectionEnabled(false);
        int dialogResult = saveFileDialog.showSaveDialog(this.getFrame());
        if (dialogResult == JFileChooser.APPROVE_OPTION)
        {
            File selFile = saveFileDialog.getSelectedFile();
            if (!selFile.getName().endsWith(".todo.xml"))
                selFile = new File(selFile.getPath()+".todo.xml");
            saveToFile(selFile);
        }
    }
}
